import pprint
from src.find_kv_and_check_word.tools_zwy_lfw import *
from src.tools.information_exchange import pub_gen

class TextD:
    def __init__(self, isAppointIndex=False, sectionIndex=0, bodyChildIndex=0, author='Iot', targetText='str', isCaseSensitive=True, isWholeWord=True, isHighLight=True, commentText='', red=255, green=255, blue=0):
        self.isAppointIndex = isAppointIndex
        self.sectionIndex = sectionIndex
        self.bodyChildIndex = bodyChildIndex
        self.author = author
        self.targetText = targetText
        self.isCaseSensitive = isCaseSensitive
        self.isWholeWord = isWholeWord  
        self.isHighLight = isHighLight
        self.commentText = commentText
        self.red = red
        self.green = green
        self.blue = blue

def get_textDtoList(file_id_list, result, KV_results):
    textDtoList_list = []
    for file_id in file_id_list:
        textDtoList = []
        file_data_general = KV_results
        file_data = get_dict_by_id(file_id,file_data_general)

        for kv in file_data['kv_json']:
            target_text = kv['value'][0]['content']
            # print(target_text)
            sectionIndex = kv['value'][0]['sectionIndex']
            bodyChildIndex = kv['value'][0]['bodyChildIndex']
            # 获取批注信息
            commentText = ""
            # 颜色未定义，默认为黄色
            textD = TextD(sectionIndex=sectionIndex, bodyChildIndex=bodyChildIndex, targetText=target_text, commentText=commentText)
            textDtoList.append(vars(textD))

        annotations = get_annotations(KV_results, file_id, result)
        for commentText,new_commentText in zip(textDtoList,annotations):
            commentText['commentText'] = new_commentText

        textDtoList_list.append({
            "fileId": file_id,
            "textDtoList": textDtoList
        })
    return textDtoList_list

def get_textDto(file_id, result, KV_results, document_name):
    textDtoList = []
    file_data_general = KV_results
    print(f"{file_id}  {KV_results}")
    file_data = get_dict_by_id(file_id, file_data_general)

    for kv in file_data['kv_json']:
        target_text = kv['value'][0]['content']
        # print(target_text)
        sectionIndex = kv['value'][0]['sectionIndex']
        bodyChildIndex = kv['value'][0]['bodyChildIndex']
        # 获取批注信息
        commentText = ""
        # 颜色未定义，默认为黄色
        textD = TextD(sectionIndex=sectionIndex, bodyChildIndex=bodyChildIndex, targetText=target_text, commentText=commentText)
        textDtoList.append(vars(textD))

    annotations = get_annotations(KV_results, file_id, result, document_name)
    for commentText,new_commentText in zip(textDtoList,annotations):
        commentText['commentText'] = new_commentText

    textDto = {
        "fileId": file_id,
        "textDtoList": textDtoList
    }
    pprint.pprint(textDto)
    return textDto

def get_textDto_singe_file(sourse_file_id, final, task_id, file_info):
    md_results = final[0]
    kv_results = final[1]
    values_based_results = final[2]
    textDtoList = []
    if not kv_results:
        return {
        "fileId": sourse_file_id,
        "textDtoList": textDtoList
    }
    file_data = kv_results[0]
    annotations_location = extract_text(kv_results)
    annotation_dict = {a["kv_index"]: a["value"] for a in annotations_location}
    for item in get_dict_by_id(sourse_file_id, md_results)['result']:
        if "index" in item and item["index"] in annotation_dict:
            item["location"] = annotation_dict[item["index"]]
        else: item["location"] = ""

    commentText_list = compare_values(values_based_results, md_results, sourse_file_id)
    for kv in file_data['kv_json']:
        target_text = kv['value'][0]['content']
        sectionIndex = kv['value'][0]['sectionIndex']
        bodyChildIndex = kv['value'][0]['bodyChildIndex']
        # 获取批注信息
        commentText = ""
        for new_commentText in commentText_list:
            if new_commentText['index'] == kv['kv_index']:
                # print(kv['kv_index'])
                # print(new_commentText['annotations'])
                commentText = new_commentText['annotations']
                pub_gen(task_id, commentText, file_info.get("docId"), file_info.get("taskDocId"))
        # 颜色未定义，默认为黄色
        textD = TextD(sectionIndex=sectionIndex, bodyChildIndex=bodyChildIndex, targetText=target_text,
                      commentText=commentText)
        textDtoList.append(vars(textD))

    pprint.pprint(textDtoList)

    return {
        "fileId": sourse_file_id,
        "textDtoList": textDtoList
    }

def compare_values(values_based_results, md_results, file_id):
    # 加载数据
    values_based_results = get_dict_by_id(file_id, values_based_results)
    if values_based_results is None:
        print("无法加载 data_json 文件。")
        exit(1)

    md_results = get_dict_by_id(file_id, md_results)
    if md_results is None:
        print("无法加载 md_results 文件。")
        exit(1)

    # 创建一个字典来快速查找model_first_output的结果
    model_dict = {str(item['index']): item for item in md_results['result']}

    # 用于存储结果的列表
    res = []

    # 遍历values_based_results的数据
    for group in values_based_results['result']:
        value_based_index = group['value_based_index']
        # 将所有indices转换为列表形式
        indices_list = [sublist['indices'] if isinstance(sublist['indices'], list) else [sublist['indices']] for sublist
                        in group['value_based_group']]

        # print(indices_list)

        # 对于每个indices，对比其他的indices
        for i, current_indices in enumerate(indices_list):
            other_indices = [idx for j, sublist in enumerate(indices_list) if j != i for idx in sublist]

            for current_index in current_indices:
                current_value = model_dict[str(current_index)]['value']
                current_object = model_dict[str(current_index)]['object']

                output_parts = []
                is_consistent = True  # 假设初始是一致的
                # print(f"current_index={current_index}")
                for other_index in other_indices:
                    # print(f"current_value={current_value}")
                    # print(f"other_index={other_index}")
                    other_value = model_dict[str(other_index)].get('value')
                    other_object = model_dict[str(other_index)].get('object')
                    other_location = model_dict[str(other_index)].get('location')
                    # print("other_location is :", type(other_location), other_location)
                        
                    if current_value != other_value:
                        if other_location is not None and other_location != 'None' and other_location != '':
                            # 如果'other_location'非空，输出为"与 '“{other_location}”中的“{other_object}{other_value}”' 不一致"
                            output_parts.append(f"“{other_location}”中的“{other_object}”“{other_value}”")
                        else:
                            # 如果'other_location'为空，输出为"与 '本文档中的“{other_object}{other_value}”' 不一致"
                            output_parts.append(f"本文档中的“{other_object}”“{other_value}”")
                        is_consistent = False  # 发现不一致

                # 将结果添加到res列表中
                if is_consistent:
                    # res.append('')
                    continue
                elif output_parts:  # 确保有输出部分再添加
                    # print(output_parts)
                    res.append(
                        {
                            "index": current_index,
                            "annotations": f"与{'、'.join(output_parts)}不一致；"
                        }
                    )

    # 输出最终结果列表
    return res
    